package club.twelveblog.tblog.service;

import club.twelveblog.tblog.common.config.AliOssClient;
import club.twelveblog.tblog.common.config.GlobalConfig;
import club.twelveblog.tblog.common.constants.SessionConstants;
import club.twelveblog.tblog.common.enums.ExceptionEnum;
import club.twelveblog.tblog.common.exception.BlogException;
import club.twelveblog.tblog.dao.UserDao;
import club.twelveblog.tblog.entity.Comment;
import club.twelveblog.tblog.entity.User;
import club.twelveblog.tblog.utils.ReNameImage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据用户id查找指定用户个人信息
     *
     * @param user_id
     * @return
     */
    public Optional<User> findUserById(Long user_id) {
        Optional<User> user = userDao.findById(user_id);
        return user;
    }

    /**
     * 用户头像上传
     *
     * @param file
     * @return
     */
    public String UploadUserImg(MultipartFile file) {
        //用于存储图片访问路径
        String url = "";

        try {
            /// 创建新实例
            AliOssClient client = new AliOssClient();
            // 连接需要的信息
            client.setAccessKeyId(GlobalConfig.ACCESSKEYID);
            client.setAccessKeySecret(GlobalConfig.ACCESSKEYSECRET);
            client.setEndpoint(GlobalConfig.ENDPOINT);
            //调用重命名方法
            String fileName = ReNameImage.renameFile(file);
            // 获得文件流
            InputStream inputStream = file.getInputStream();
            //上传到OSS
            client.putObject(GlobalConfig.BUCKETNAME, "authorImg/" + fileName, inputStream);
            System.out.println("图片下载url是:" + url);
            url += "https://tblog.oss-cn-beijing.aliyuncs.com/authorImg/" + fileName;
            return url;
        } catch (IOException e) {
            //上传失败
            log.error("上传图片失败", e);
            throw new BlogException(ExceptionEnum.UPLOADIMAGE_ERROR);
        }
    }

    public void saveUser(User user) {
        userDao.save(user);
    }

    /**
     * 更新用户账号状态
     *
     * @param user
     */
    @Transactional
    public void updateUserStatus(User user) {
        User user1 = userDao.getOne(user.getUser_id());
        user1.setUser_locked(user.getUser_locked());
        try {
            userDao.save(user1);
        } catch (BlogException e) {
            throw new BlogException(ExceptionEnum.UPDATE_FAILED);
        }

    }

    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    public Page<User> findAllUserByPage(int page) {
        //显示第一页每页显示5条,默认从0开始
        PageRequest pageRequest = PageRequest.of(page - 1, 3);
        return userDao.findAll(pageRequest);
    }

    /**
     * 修改用户的个人信息
     *
     * @param user
     */
    @Transactional
    public void updateUserInfo(User user) {

            User updateUser = userDao.getOne(SessionConstants.USER_ID);
            updateUser.setPassword(user.getPassword());
            updateUser.setSex(user.getSex());
            updateUser.setIntroduction(user.getIntroduction());
            updateUser.setEmail(user.getEmail());
            updateUser.setBirthday(user.getBirthday());
            updateUser.setAddress(user.getAddress());
            updateUser.setAuthorImg(user.getAuthorImg());
            userDao.save(updateUser);

    }

    /**
     * 修改用户头像信息
     * @param url
     */
    public void updateImage(String url) {
        User one = userDao.getOne(SessionConstants.USER_ID);
        one.setAuthorImg(url);
        userDao.save(one);
    }

    /**
     * 判断用户名是否存在
     * @param username
     * @return boolean
     */

    public boolean isExist(String username){
       User user=userDao.findByUsername(username);
       //如果用户已经不存在，那么返回false
        //用户存在，user就不为null，那么就返回true
        return null!=user;
    }

    /**
     * 用户注册
     */
    public void userRegister(User user){
        userDao.save(user);
    }

    /**
     * 登录
     *
     * @param
     * @return
     */
    public User login(String username, String password) {
        User user = userDao.findByUsername(username);
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(user!=null){
            boolean b = user.getPassword().equals(md5Password);//b为真则存在该用户
            if (b!=true){
                return null;
            }else {
                return user;
            }
        }else {
            return null;
        }
    }

    /**
     * 判断用户状态
     * @param
     * @return
     */
    public boolean islock(String username){
        int a=userDao.isLock(username);
        boolean b=true;
        if (a!=1){
            b=false;
        }else {
            b=true;
        }

        return b;
    }
    public Object getOne(Long user_id) {
        User one = userDao.getOne(user_id);
        return one;
    }

    public Object getRedisValue(){

        Object o = redisTemplate.opsForValue().get("88888888");
        Boolean key = redisTemplate.hasKey("88888888");
        System.out.println(key);
        System.out.println("通过get(Object key)方法获取set(K key, V value)方法新增的字符串值:"+o);
        return o;
    }
    public void setRedisValue(){

        redisTemplate.opsForValue().set("88888888","3");

    }


}
